import { JS_CONTEXT } from '@/constants'
import Cookie from 'js-cookie'

const headers = new Headers()
headers.append('content-type', 'application/json')
headers.append('token', Cookie.get('token'))

/**
 * 请求中间件
 * @param to 前往路由
 * @param from 来自路由
 */
export const requestMiddleware = async (to, from) => {
  const url = process.env.VUE_APP_BUILD_MODE === 'static' ? './config.json' : '/config.json'
  const response = await fetch(url)
  if (response.status === 200) {
    const config = JSON.parse(await response.text())
    if (window.localStorage) {
      window.localStorage.setItem('IP', config.IP)
      window.localStorage.setItem('PORT', config.PORT)
      window.localStorage.setItem('PROTOCOL', config.PROTOCOL)
      window.localStorage.setItem('PROTOCOL_WEBSOCKET', config.PROTOCOL_WEBSOCKET)
      window.localStorage.setItem('PROJECT', config.PROJECT)
      window.localStorage.setItem('CORP_ID', config.CORP_ID)
      JS_CONTEXT.BASE_URL = window.localStorage.getItem('PROTOCOL') + '://' +
        window.localStorage.getItem('IP') + ':' +
        window.localStorage.getItem('PORT') + '/' +
        window.localStorage.getItem('PROJECT')
    } else {
      alert('当前浏览器不支持localStorage，请升级版本')
    }
  }
}
